<template>
  <div class="app-container">
    <el-container>
      <el-header style="height: auto; margin-bottom: 10px">
        <el-row :gutter="2" type="flex">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-row>
              <el-col :xs="24" :sm="24" :md="12" :lg="5" :xl="5">
                <el-select v-model="sop_id" style="width: 70%" size="mini" placeholder="选择SOP分类" clearable filterable @change="handleSearchSOP">
                  <el-option
                    v-for="category in sop_categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
                <el-button
                  style="width: 20%"
                  size="mini"
                  type="warning"
                  title="管理"
                  icon="el-icon-setting"
                  @click="handleManageSOP"
                />
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="2" :xl="2">
                <el-button
                  type="success"
                  size="mini"
                  title="添加顶级节点"
                  icon="el-icon-plus"
                  @click="showAddNewModel"
                >添加顶级节点
                </el-button>
              </el-col>
              <el-col :xs="24" :sm="24" :md="12" :lg="7" :xl="7">
                <el-row :gutter="20">
                  <el-col :span="24">
                    <el-input
                      v-model="kwInput"
                      size="mini"
                      placeholder="输入关键词进行筛选"
                      class="input-with-select"
                      clearable
                      @keyup.native.enter="handleSearch"
                    >
                      <el-button slot="append" size="mini" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                    </el-input>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-aside width="400px" class="fixed-aside">
          <el-row>
            <el-col :span="24">
              <div class="navigation-wrapper">
                <el-button
                  type="text"
                  class="nav-button"
                  @click="handleToTopNode()"
                >
                  返回顶层
                </el-button>
                <template v-if="current_expended_node && current_expended_node.parent_id">
                  <el-divider direction="vertical" />
                  <el-tooltip
                    :content="current_expended_node.parent_name + current_expended_node.parent_id"
                    placement="top"
                  >
                    <el-button
                      type="text"
                      class="nav-button"
                      @click="handleIDSearch(current_expended_node.parent_id)"
                    >
                      {{ '返回:' + current_expended_node.parent_name }}
                    </el-button>
                  </el-tooltip>
                </template>
                <template v-else>
                  <el-divider direction="vertical" />
                  <span v-if="current_expended_node" class="current-node-name">
                    {{ current_expended_node.name }}
                  </span>
                </template>

                <!-- 当前节点的操作按钮 -->
                <template v-if="current_expended_node">
                  <div class="node-action-buttons">
                    <el-button
                      type="success"
                      size="mini"
                      icon="el-icon-plus"
                      @click.stop="() => append(current_expended_node)"
                    />
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      @click.stop="handleDirectlyEditModel(current_expended_node)"
                    />
                  </div>
                </template>
              </div>
            </el-col>
          </el-row>
          <el-tree
            ref="ModelTree"
            v-loading="listLoading"
            :data="data"
            :accordion="true"
            :load="loadNode"
            lazy
            :expand-on-click-node="false"
            node-key="id"
            highlight-current
            :default-expanded-keys="expanded_ids"
            :indent="12"
            :props="{ children: 'children', label: 'name' }"
            draggable
            @node-drop="handleNodeDrop"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <div class="node-title" @click="handleSearchNodeByParentID(data)">
                <span
                  :class="{
                    'name-text': true,
                    // 'disabled': data.disabled,
                    'editing': formVisible && form.id === data.id
                  }"
                >
                  {{ data.parent_id && data.name.length > 0 ? data.name : data.name }}
                </span>
                <span v-if="data.children_count" class="children-count">{{ data.children_count }}</span>
              </div>
              <div class="node-info-actions">
                <div class="node-actions">

                  <el-button type="success" size="mini" icon="el-icon-plus" @click.stop="() => append(data)" />

                  <el-button type="primary" size="mini" icon="el-icon-edit" @click.stop="handleDirectlyEditModel(data)" />

                  <el-button type="danger" size="mini" icon="el-icon-delete" @click.stop="handleClickDelete(data)" />

                </div>
              </div>
            </span>
          </el-tree>
        </el-aside>
        <el-main v-loading="dataloading" class="scrollable-main">
          <el-card v-if="formVisible">
            <div slot="header" class="card-header">
              <span>{{ formTitle }}</span>
              <div>
                <el-button type="success" size="small" :loading="formLoading" @click="handleSave">
                  <i :class="{'el-icon-success': saveSuccess, 'el-icon-upload': !saveSuccess}" />
                  {{ saveSuccess ? '已保存' : '保存' }}
                </el-button>
                <el-button type="primary" size="small" :disabled="!form.id" @click="handleTest">测试</el-button>
                <el-button size="small" @click="formVisible = false">取消</el-button>
              </div>
            </div>

            <el-form v-loading="formLoading" :model="form" label-position="top" label-width="120px">
              <el-tabs v-model="activeTab">
                <!-- 基本信息标签页 -->
                <el-tab-pane label="基本信息" name="basic">
                  <!-- 父节点信息 -->
                  <div v-if="form.id" class="form-section parent-section">
                    <div class="section-title">父节点信息</div>
                    <div class="form-inline-group">
                      <el-tag type="info" class="parent-tag">{{ form.parent_name }}</el-tag>
                      <el-input v-model="form.parent_id" placeholder="父节点ID" size="small" class="parent-id-input">
                        <template slot="prepend">ID:</template>
                      </el-input>
                    </div>
                  </div>

                  <!-- 基本信息分组 -->
                  <div class="form-section info-section">
                    <div class="section-title">基本信息</div>
                    <div class="form-flex-group">
                      <el-form-item label="名称" class="form-item-flex">
                        <el-input v-model="form.name" placeholder="请输入名称" />
                      </el-form-item>
                      <el-form-item label="SOP分类" class="form-item-flex">
                        <el-select v-model="form.sop" placeholder="请选择SOP分类" style="width: 100%">
                          <el-option
                            v-for="category in sop_categories"
                            :key="category.id"
                            :label="category.name"
                            :value="category.id"
                          />
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>

                  <!-- 设置信息 -->
                  <div class="form-section settings-section">
                    <div class="section-title">设置</div>
                    <div class="form-flex-group">
                      <el-form-item label="可以执行" class="form-item-small">
                        <el-switch
                          v-model="form.disabled"
                          active-color="#ff4949"
                          inactive-color="#13ce66"
                          :active-value="true"
                          :inactive-value="false"
                        />
                      </el-form-item>
                      <el-form-item label="默认AI模型" class="form-item-medium">
                        <el-select v-model="form.engine" placeholder="请选择AI模型" style="width: 100%">
                          <el-option
                            v-for="item in ai_engines"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="颜色" class="form-item-small">
                        <div class="color-selection-container">
                          <el-color-picker v-model="form.color" :predefine="predefineColors" />
                          <span class="color-preview" :style="{backgroundColor: form.color}" />
                        </div>
                      </el-form-item>
                      <el-form-item label="排序" class="form-item-small">
                        <el-input v-model="form.position" placeholder="输入序号(数字)" type="number" min="0" />
                      </el-form-item>
                      <el-form-item v-if="this.$store.getters.roles.indexOf('admin') !== -1" label="最小vip等级" class="form-item-small">
                        <el-input v-model="form.vip_grade" type="number" max="5" />
                      </el-form-item>
                    </div>
                  </div>

                  <!-- AI类型和图片参数 -->
                  <div class="form-section ai-type-section">
                    <div class="section-title">AI类型和图片参数</div>
                    <div class="form-flex-group">
                      <el-form-item label="AI类型" class="form-item-medium">
                        <el-select v-model="form.ai_type" placeholder="请选择AI类型" style="width: 100%">
                          <el-option label="文字对话" value="text" />
                          <el-option label="图片生成" value="image" />
                          <el-option label="综合" value="comprehensive" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="图片宽高比" class="form-item-medium" :title="'图片宽高比参数,如:16:9, 1:1, 2:3等'">
                        <el-select v-model="form.aspect_ratio" placeholder="请选择宽高比" clearable style="width: 100%">
                          <el-option label="1:1 (方形)" value="1:1" />
                          <el-option label="16:9 (宽屏)" value="16:9" />
                          <el-option label="9:16 (竖屏)" value="9:16" />
                          <el-option label="2:3" value="2:3" />
                          <el-option label="3:2" value="3:2" />
                          <el-option label="3:4" value="3:4" />
                          <el-option label="4:3" value="4:3" />
                          <el-option label="4:5" value="4:5" />
                          <el-option label="5:4" value="5:4" />
                          <el-option label="21:9 (超宽)" value="21:9" />
                        </el-select>
                      </el-form-item>
                      <el-form-item label="图片分辨率" class="form-item-small" :title="'图片分辨率参数,如:1K, 2K, 4K(必须大写K)'">
                        <el-select v-model="form.resolution" placeholder="请选择分辨率" clearable style="width: 100%">
                          <el-option label="1K" value="1K" />
                          <el-option label="2K" value="2K" />
                          <el-option label="4K" value="4K" />
                        </el-select>
                      </el-form-item>
                    </div>
                  </div>

                  <!-- 用户输入提示 -->
                  <div class="form-section prompt-section">
                    <div class="section-title">用户输入提示</div>
                    <el-input v-model="form.placeholder" type="textarea" :rows="3" placeholder="提示用户输入什么" />
                  </div>
                </el-tab-pane>

                <!-- 提示词设置标签页 -->
                <el-tab-pane label="提示词设置" name="prompt">
                  <el-form-item>
                    <el-radio-group v-model="usePromptTemplate" @change="handlePromptTypeChange">
                      <el-radio :label="true">使用模板ID</el-radio>
                      <el-radio :label="false">自定义提示词</el-radio>
                    </el-radio-group>
                  </el-form-item>

                  <!-- 模板ID选择 -->
                  <el-form-item v-if="usePromptTemplate" label="prompt模板ID">
                    <el-select
                      v-model="form.aiprompt_id"
                      placeholder="输入名称搜索创建好的prompt模板"
                      filterable
                      remote
                      reserve-keyword
                      style="width: 100%"
                      :remote-method="remoteSearchAiPrompt"
                      :loading="aipromptLoading"
                    >
                      <el-option
                        v-for="item in aiprompts"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                        <span style="float: left">{{ item.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">ID: {{ item.id }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <!-- 自定义提示词输入 -->
                  <div v-if="!usePromptTemplate" class="form-section prompt-editor">
                    <div class="section-title">提示词编辑器</div>
                    <mavon-editor
                      key="prompt-editor"
                      v-model="form.prompt"
                      :toolbars="promptToolbars"
                      :box-shadow="false"
                      :default-open="'edit'"
                      placeholder="输入提示词模板"
                      class="md-editor"
                    >
                      <template slot="left-toolbar-before">
                        <button
                          type="button"
                          class="op-icon fa fa-user-o"
                          aria-hidden="true"
                          title="插入用户内容变量"
                          style="color: #409EFF; font-weight: bold;"
                          @click="insertUserContent"
                        >U</button>
                      </template>
                    </mavon-editor>
                    <el-alert
                      type="info"
                      :title="userContentTip"
                      :closable="false"
                      show-icon
                      style="margin-top: 10px;"
                    />
                  </div>
                </el-tab-pane>

                <!-- 输出设置标签页 -->
                <el-tab-pane label="输出模板" name="output">
                  <el-form-item label="输出模板">
                    <div class="editor-container">
                      <mavon-editor
                        key="output-editor"
                        ref="outputEditor"
                        v-model="form.output_template"
                        :toolbars="outputToolbars"
                        :box-shadow="false"
                        :default-open="'edit'"
                        placeholder="请输入输出模板，支持Markdown格式"
                        class="md-editor"
                      >
                        <template slot="left-toolbar-before">
                          <button
                            type="button"
                            class="op-icon fa fa-user-o"
                            aria-hidden="true"
                            title="插入用户内容变量"
                            style="color: #409EFF; font-weight: bold;"
                            @click="insertUserContent"
                          />
                        </template>
                      </mavon-editor>
                    </div>

                  </el-form-item>
                </el-tab-pane>

                <!-- 参考素材标签页 -->
                <el-tab-pane v-if="form.id" label="参考素材" name="references">
                  <div class="references-container">
                    <!-- 上传组件 -->
                    <el-row>
                      <el-col :span="24">
                        <crmfilequickuploader
                          :directory-name="'AIModelTreeFiles'"
                          @insert="handleInsertFile"
                        />
                      </el-col>
                    </el-row>

                    <!-- 精简工具栏 -->
                    <el-row class="compact-toolbar" :gutter="10">
                      <el-col :span="12">
                        <el-button
                          v-if="selectedReferences.length > 0"
                          type="danger"
                          size="mini"
                          icon="el-icon-delete"
                          @click="batchDeleteReferences"
                        >
                          批量删除 ({{ selectedReferences.length }})
                        </el-button>
                      </el-col>
                      <el-col :span="12" class="text-right">
                        <el-button
                          type="primary"
                          size="mini"
                          icon="el-icon-refresh"
                          @click="loadReferences"
                        >
                          刷新
                        </el-button>
                      </el-col>
                    </el-row>

                    <!-- 文件卡片视图 -->
                    <div v-loading="referencesLoading" class="files-grid-container">
                      <el-row :gutter="8">
                        <el-col
                          v-for="item in references"
                          :key="item.id"
                          :span="4"
                          class="mb-8"
                        >
                          <div
                            class="compact-file-card"
                            :class="{ 'selected': isReferenceSelected(item) }"
                            @click="handleFileCardClick(item, $event)"
                          >
                            <div class="file-icon-container">
                              <!-- 图片预览 -->
                              <div
                                v-if="isImageFile(item)"
                                class="image-preview-container"
                                @click.stop="previewImage(item.file_url)"
                              >
                                <el-image
                                  :src="item.file_url"
                                  fit="cover"
                                  class="small-file-icon"
                                  lazy
                                >
                                  <div slot="error" class="image-error">
                                    <i class="el-icon-picture-outline" />
                                  </div>
                                </el-image>
                              </div>
                              <!-- 文件图标 -->
                              <i
                                v-else-if="isPDF(item.filename)"
                                class="el-icon-document"
                                style="font-size: 48px; color: #e74c3c;"
                              />
                              <i
                                v-else-if="isExcel(item.filename)"
                                class="el-icon-document"
                                style="font-size: 48px; color: #27ae60;"
                              />
                              <i
                                v-else-if="isWord(item.filename)"
                                class="el-icon-document"
                                style="font-size: 48px; color: #2980b9;"
                              />
                              <i
                                v-else
                                class="el-icon-document"
                                style="font-size: 48px; color: #95a5a6;"
                              />
                            </div>
                            <div class="file-info">
                              <el-tooltip :content="item.filename" placement="top">
                                <div class="file-name">{{ truncateFileName(item.filename || '未命名文件') }}</div>
                              </el-tooltip>
                              <div class="file-meta">
                                <span class="file-type">{{ getFileTypeLabel(item.file_type) }}</span>
                                <span class="file-date">{{ formatShortDate(item.created_at) }}</span>
                              </div>
                              <!-- 描述输入框 -->
                              <el-input
                                v-model="item.description"
                                type="textarea"
                                :rows="1"
                                size="mini"
                                placeholder="添加描述"
                                @blur="updateReferenceDescription(item)"
                                @click.stop
                              />
                            </div>
                            <div class="file-actions">
                              <el-button
                                type="text"
                                size="mini"
                                icon="el-icon-download"
                                @click.stop="downloadFile(item)"
                              />
                              <el-button
                                type="text"
                                size="mini"
                                icon="el-icon-delete"
                                class="danger-btn"
                                @click.stop="deleteReference(item)"
                              />
                            </div>
                          </div>
                        </el-col>
                        <!-- 空状态 -->
                        <el-col v-if="references.length === 0 && !referencesLoading" :span="24">
                          <div class="empty-state">
                            <i class="el-icon-folder-opened" style="font-size: 48px; color: #C0C4CC;" />
                            <p>暂无参考素材，请上传文件</p>
                          </div>
                        </el-col>
                      </el-row>
                    </div>
                  </div>
                </el-tab-pane>

                <!-- 高级信息标签页 -->
                <el-tab-pane v-if="form.id" label="信息记录" name="info">
                  <div class="info-table">
                    <el-row v-if="form.create_at" :gutter="20">
                      <el-col :span="6"><strong>创建时间:</strong></el-col>
                      <el-col :span="18">{{ form.create_at }}</el-col>
                    </el-row>
                    <el-row v-if="form.update_at" :gutter="20">
                      <el-col :span="6"><strong>更新时间:</strong></el-col>
                      <el-col :span="18">{{ form.update_at }}</el-col>
                    </el-row>
                    <el-row v-if="form.id" :gutter="20">
                      <el-col :span="6"><strong>ID:</strong></el-col>
                      <el-col :span="18">{{ form.id }}</el-col>
                    </el-row>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-form>
          </el-card>

          <div v-else class="empty-state">
            <i class="el-icon-document" style="font-size: 50px; color: #ddd;" />
            <p style="color: #999; margin-top: 15px;">请选择或添加一个AI模型</p>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 确认删除对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteVisible"
      width="30%"
    >
      <span>确定要删除模型 "{{ deleteModel.name }}" 吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteVisible = false">取消</el-button>
        <el-button type="danger" :loading="deleteLoading" @click="confirmDelete">确定</el-button>
      </span>
    </el-dialog>

    <!-- SOP管理对话框 -->
    <el-dialog
      title="SOP管理"
      :visible.sync="sopManageDialogVisible"
      width="800px"
      :before-close="handleCloseSopDialog"
    >
      <div style="margin-bottom: 20px;">
        <el-button type="primary" size="small" @click="showAddSOP">新增SOP</el-button>
      </div>

      <el-table :data="sop_categories" border style="width: 100%">
        <el-table-column prop="name" label="SOP名称" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.description || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="关联项目" min-width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.projects && scope.row.projects.length > 0">
              <el-tag
                v-for="project in scope.row.projects.slice(0, 2)"
                :key="project.id"
                size="mini"
                style="margin-right: 5px; margin-bottom: 2px;"
              >
                {{ project.name }}
              </el-tag>
              <el-tag v-if="scope.row.projects.length > 2" size="mini" type="info">
                +{{ scope.row.projects.length - 2 }}
              </el-tag>
            </span>
            <span v-else style="color: #999;">未关联</span>
          </template>
        </el-table-column>
        <el-table-column label="使用次数" width="80">
          <template slot-scope="scope">
            <el-tag size="mini">{{ getSOPUsageCount(scope.row.name) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="editSOP(scope.row, scope.$index)"
            >编辑</el-button>
            <el-button
              type="text"
              size="small"
              style="color: #f56c6c;"
              @click="deleteSOP(scope.row, scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加/编辑SOP表单 -->
      <el-form
        v-if="editingSOP !== null"
        ref="sopManageForm"
        :model="sopManageForm"
        :rules="sopManageRules"
        style="margin-top: 20px; padding: 20px; border: 1px solid #e4e7ed; border-radius: 4px; background-color: #f9f9f9;"
      >
        <el-form-item label="SOP名称" prop="name">
          <el-input v-model="sopManageForm.name" placeholder="请输入SOP名称" />
        </el-form-item>
        <el-form-item label="SOP描述">
          <el-input v-model="sopManageForm.description" type="textarea" rows="3" placeholder="请输入SOP描述" />
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="sopManageForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="sopManageForm.sort_order" type="number" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="关联项目">
          <el-select
            v-model="sopManageForm.project_ids"
            multiple
            filterable
            placeholder="请选择关联的项目"
            style="width: 100%"
            :loading="projectsLoading"
            @focus="loadProjects"
          >
            <el-option
              v-for="project in projects"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveSOP">保存</el-button>
          <el-button @click="cancelEditSOP">取消</el-button>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="sopManageDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="imagePreviewVisible"
      width="80%"
      top="20px"
      append-to-body
    >
      <div class="image-preview-container">
        <img
          :src="currentPreviewImage"
          alt="预览图片"
          style="width: 100%; height: auto; max-height: 70vh; object-fit: contain;"
        >
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" icon="el-icon-copy-document" @click="copyImageUrl">复制图片链接</el-button>
        <el-button @click="imagePreviewVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete, Tree, GetSopNames } from '@/api/cms/aimodeltree'
import { Get as GetAiPrompt } from '@/api/cms/aiprompt'
import { Get as GetSOPCategory, Post as PostSOPCategory, Put as PutSOPCategory, Delete as DeleteSOPCategory } from '@/api/cms/sopcategory'
import { Get as GetProject } from '@/api/erp/elicink/project'
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
import { getReferences, addReference, updateReference, deleteReference, batchReferences } from '@/api/cms/references'
import qs from 'qs'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import Crmfilequickuploader from '@/components/crmfilequickuploader'

export default {
  name: 'AiModelTreeManager',
  components: {
    mavonEditor,
    Crmfilequickuploader
  },
  data() {
    return {
      // 树形数据
      data: [],
      total: 0,
      userContentTip: '使用 {{user_content}} 来引用用户输入内容,预处理插件语法[[RPID_%s]]',
      // 加载状态
      listLoading: false,
      // 过滤文本
      filterText: '',
      // SOP分类列表
      sop_categories: [],
      // 当前选择的SOP ID
      sop_id: null,
      // 当前选择的SOP名称（用于显示）
      sop_name: '',
      // 保持向后兼容的SOP名称列表
      sop_names: [],

      // SOP管理对话框
      sopManageDialogVisible: false,
      sopManageForm: {
        id: null,
        name: '',
        description: '',
        icon: 'ai-robot',
        sort_order: 0,
        is_active: true,
        project_ids: []
      },
      sopManageRules: {
        name: [
          { required: true, message: '请输入SOP名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      },
      editingSOP: null,
      // 项目列表
      projects: [],
      projectsLoading: false,
      // 展开的节点ID
      expanded_ids: [],
      // 当前展开的节点
      current_expended_node: null,
      // 搜索关键词
      kwInput: '',
      keyword: '',
      engine: '',
      // 更多过滤选项
      more_filter: false,

      // 提示词编辑器工具栏配置
      promptToolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        help: true, // 帮助
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        navigation: true, // 导航目录
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        preview: true // 预览
      },

      // 输出模板编辑器工具栏配置
      outputToolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        help: true, // 帮助
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        navigation: true, // 导航目录
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        preview: true // 预览
      },

      // 表单相关
      formVisible: false,
      formTitle: '编辑模型',
      formLoading: false,
      dataloading: false,
      saveSuccess: false,
      activeTab: 'basic',
      form: {
        id: '',
        name: '',
        vip_grade: 0,
        sop: null, // 新的SOP外键字段
        sop_name: '', // 保留原字段用于向后兼容
        parent_id: '',
        parent_name: '',
        disabled: false,
        engine: 'claude-3.7-sonnet',
        color: '#409EFF',
        position: '',
        placeholder: '',
        prompt: '',
        aiprompt_id: '',
        // AI类型和图片生成参数
        ai_type: 'text', // AI类型: text-文字对话, image-图片生成, comprehensive-综合
        aspect_ratio: '', // 图片宽高比参数
        resolution: '' // 图片分辨率参数
      },
      usePromptTemplate: true,
      aiprompts: [],
      aipromptLoading: false,

      // 参考素材相关
      references: [],
      referencesLoading: false,
      selectedReferences: [],
      // 图片预览相关
      imagePreviewVisible: false,
      currentPreviewImage: '',

      // AI引擎选项
      ai_engines: [
        { value: 'gpt-4o', label: 'gpt-4o' },
        { value: 'claude-3.7-sonnet', label: 'claude-3.7-sonnet' }
      ],

      // 预定义颜色
      predefineColors: [
        '#f56c6c', // 红色
        '#e6a23c', // 橙色
        '#E6CF00', // 金黄色
        '#409EFF', // 蓝色
        '#67c23a', // 绿色
        '#909399', // 灰色
        '#9B55FF', // 紫色
        '#9F8170', // 棕色
        '#00CCCC', // 青色
        '#CC6699', // 粉红
        '#6B5152', // 暗红
        '#336699' // 深蓝
      ],

      // 删除相关
      deleteVisible: false,
      deleteModel: {},
      deleteLoading: false
    }
  },
  computed: {
    uploadHeaders() {
      return {
        Authorization: getToken(),
        PTOKEN: this.$store.getters.projectId
      }
    },
    uploadData() {
      return {
        project_id: this.$store.getters.projectId
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.ModelTree.filter(val)
    }
  },
  created() {
    this.fetchData()
    // 从本地存储中恢复展开的节点
    this.restoreExpandedState()
    // 获取AI引擎列表
    this.getAiEngines()
  },
  methods: {
    // 恢复展开状态
    restoreExpandedState() {
      const expandedKey = `${this.sop_id}_expanded_ids`
      const savedExpandedIds = localStorage.getItem(expandedKey)
      if (savedExpandedIds) {
        try {
          this.expanded_ids = JSON.parse(savedExpandedIds)
          // 同时恢复当前展开节点
          const currentNodeKey = `${this.sop_id}_current_node`
          const savedCurrentNode = localStorage.getItem(currentNodeKey)
          if (savedCurrentNode) {
            this.current_expended_node = JSON.parse(savedCurrentNode)
          }
        } catch (e) {
          console.error('恢复展开状态失败:', e)
        }
      }
    },
    // 保存展开状态
    saveExpandedState() {
      const expandedKey = `${this.sop_id}_expanded_ids`
      localStorage.setItem(expandedKey, JSON.stringify(this.expanded_ids))

      // 同时保存当前展开节点
      if (this.current_expended_node) {
        const currentNodeKey = `${this.sop_id}_current_node`
        localStorage.setItem(currentNodeKey, JSON.stringify(this.current_expended_node))
      }
    },
    fetchData() {
      this.listLoading = true
      // 获取SOP分类列表
      GetSopNames().then(response => {
        // 根据实际返回格式判断
        if (response.success || (response.data && response.data.success)) {
          // GetSopNames 返回格式: { success: true, data: [names...], sop_details: [objects...] }
          if (response.sop_details && response.sop_details.length > 0) {
            this.sop_categories = response.sop_details
          } else {
            // 如果没有 sop_details，但有 data，构造对象
            const sopNames = response.data || []
            this.sop_categories = sopNames.map((name, index) => ({
              id: index + 1,
              name: name,
              description: `${name}相关的AI智能SOP`
            }))
          }

          // 保持向后兼容，生成sop_names数组
          this.sop_names = this.sop_categories.map(cat => cat.name)

          // 设置默认选择第一个SOP
          if (this.sop_categories.length > 0) {
            this.sop_id = this.sop_categories[0].id
            this.sop_name = this.sop_categories[0].name
          }

          console.log('加载SOP分类成功:', this.sop_categories)
        } else {
          // 如果获取失败，使用默认值
          this.sop_categories = [
            { id: 1, name: 'B2B业务', description: 'B2B业务相关的AI智能SOP' },
            { id: 2, name: '独立站SEO', description: '独立站SEO优化相关的AI智能SOP' },
            { id: 3, name: 'linkedin运营', description: 'LinkedIn社交媒体运营相关的AI智能SOP' }
          ]
          this.sop_names = this.sop_categories.map(cat => cat.name)
          this.sop_id = this.sop_categories[0].id
          this.sop_name = this.sop_categories[0].name
        }

        this.handleToTopNode()
      }).catch(() => {
        // 出错时使用默认值
        this.sop_categories = [
          { id: 1, name: 'B2B业务', description: 'B2B业务相关的AI智能SOP' },
          { id: 2, name: '独立站SEO', description: '独立站SEO优化相关的AI智能SOP' },
          { id: 3, name: 'linkedin运营', description: 'LinkedIn社交媒体运营相关的AI智能SOP' }
        ]
        this.sop_names = this.sop_categories.map(cat => cat.name)
        this.sop_id = this.sop_categories[0].id
        this.sop_name = this.sop_categories[0].name
        this.handleToTopNode()
      })
    },
    // 加载树节点
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.listLoading = true
        Tree('', '').then(response => {
          this.data = response.data.data
          this.total = response.data.total
          resolve(this.data)
          this.listLoading = false
        }).catch(() => {
          this.listLoading = false
          resolve([])
        })
      } else {
        // 如果是展开子节点
        const id = node.data.id
        Tree(id, '').then(response => {
          const children = response.data.data
          this.total = response.data.total
          resolve(children)
        }).catch(() => {
          resolve([])
        })
      }
    },
    // 过滤节点
    filterNode(value, data) {
      if (!value) return true
      return data.name.toLowerCase().indexOf(value.toLowerCase()) !== -1
    },
    // 判断文本是否溢出
    isOverflowing(text) {
      if (!text) return false
      return text.length > 15
    },
    // 处理节点拖放
    handleNodeDrop(draggingNode, dropNode, dropType, ev) {
      const draggingData = draggingNode.data
      const dropData = dropNode.data

      // 根据拖放类型进行不同处理
      if (dropType === 'inner') {
        // 拖到节点内部，成为子节点
        draggingData.parent_id = dropData.id
      } else if (dropType === 'before' || dropType === 'after') {
        // 拖到节点前面或后面，成为兄弟节点
        draggingData.parent_id = dropData.parent_id
      }

      // 更新节点数据
      Put(draggingData.id, draggingData).then(() => {
        this.$message.success('移动节点成功')
      }).catch(() => {
        this.$message.error('移动节点失败')
        // 刷新树以恢复原状
        this.handleToTopNode()
      })
    },
    // 搜索SOP
    handleSearchSOP() {
      // 更新当前选择的SOP名称用于显示
      const selectedCategory = this.sop_categories.find(cat => cat.id === this.sop_id)
      if (selectedCategory) {
        this.sop_name = selectedCategory.name
      }

      // 保存当前SOP的展开状态
      this.saveExpandedState()

      // 先清空tree数据，避免显示错误的数据
      this.data = []
      this.total = 0
      this.current_expended_node = null
      this.formVisible = false // 关闭编辑表单

      // 切换SOP后恢复该SOP的展开状态
      this.restoreExpandedState()

      this.handleToTopNode()
    },
    // 管理SOP
    handleManageSOP() {
      // 打开SOP管理对话框
      this.sopManageDialogVisible = true
      this.loadSOPList()
    },
    // 加载SOP列表
    loadSOPList() {
      GetSOPCategory().then(response => {
        // 根据实际返回格式判断: { success: true, data: [...] }
        if (response.success || (response.data && response.data.success)) {
          this.sop_categories = response.data || response.data.data || []
          this.sop_names = this.sop_categories.map(cat => cat.name)
        }
      }).catch(() => {
        this.$message.error('获取SOP列表失败')
      })
    },
    // 加载项目列表
    async loadProjects() {
      if (this.projects.length > 0) return // 如果已经加载过，不重复加载

      this.projectsLoading = true
      try {
        // 参考 schedule.vue 的获取方式
        const response = await GetProject(null, qs.stringify({
          pagesize: 1000, // 获取所有项目
          page: 1
        }))
        if (response.success) {
          // 根据实际API返回格式解析数据
          // 后台返回: { success: true, data: { total: 2, data: [...] } }
          const projectData = response.data.data || []
          // 只获取启用的项目
          this.projects = projectData.filter(project => project.isEnable)
          console.log('成功加载项目列表:', this.projects)
        } else {
          this.projects = []
          console.error('获取项目列表失败:', response)
        }
      } catch (error) {
        console.error('加载项目列表失败:', error)
        this.$message.error('获取项目列表失败')
        this.projects = []
      }
      this.projectsLoading = false
    },
    // 获取SOP使用次数
    getSOPUsageCount(sopName) {
      // 这里可以添加统计SOP使用次数的逻辑
      // 暂时返回0，后续可以实现
      return 0
    },
    // 显示添加SOP表单
    showAddSOP() {
      this.editingSOP = 'add'
      this.sopManageForm = {
        id: null,
        name: '',
        description: '',
        icon: 'ai-robot',
        sort_order: 0,
        is_active: true,
        project_ids: []
      }
      this.loadProjects() // 加载项目列表
    },
    // 编辑SOP
    editSOP(category, index) {
      this.editingSOP = index

      this.sopManageForm = {
        id: category.id,
        name: category.name,
        description: category.description || '',
        icon: category.icon || 'ai-robot',
        sort_order: category.sort_order || 0,
        is_active: category.is_active !== false,
        project_ids: category.projects ? category.projects.map(p => p.id) : []
      }
      this.loadProjects() // 加载项目列表
    },
    // 删除SOP
    deleteSOP(category, index) {
      this.$confirm(`确定要删除SOP "${category.name}" 吗？这将影响所有使用该SOP的AI模型。`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteSOPCategory(category.id).then(() => {
          // 从列表中移除
          this.sop_categories.splice(index, 1)
          this.sop_names = this.sop_categories.map(cat => cat.name)
          this.$message.success('删除成功')

          // 如果当前选中的是被删除的SOP，切换到第一个
          if (this.sop_id === category.id) {
            if (this.sop_categories.length > 0) {
              this.sop_id = this.sop_categories[0].id
              this.sop_name = this.sop_categories[0].name
            } else {
              this.sop_id = null
              this.sop_name = ''
            }
            this.handleToTopNode()
          }
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 保存SOP
    saveSOP() {
      this.$refs.sopManageForm.validate((valid) => {
        if (valid) {
          const sopData = { ...this.sopManageForm }
          sopData.name = sopData.name.trim()

          if (this.editingSOP === 'add') {
            // 检查是否重复
            if (this.sop_categories.some(cat => cat.name === sopData.name)) {
              this.$message.error('SOP名称已存在')
              return
            }
            // 添加新SOP
            PostSOPCategory(sopData).then(response => {
              // 根据实际返回格式判断: { success: true, data: {...} }
              if (response.success || (response.data && response.data.success)) {
                const newCategory = response.data || response.data.data
                this.sop_categories.push(newCategory)
                this.sop_names = this.sop_categories.map(cat => cat.name)
                this.$message.success('添加成功')
                this.cancelEditSOP()
              } else {
                this.$message.error('添加失败')
              }
            }).catch(() => {
              this.$message.error('添加失败')
            })
          } else {
            // 编辑现有SOP
            const originalCategory = this.sop_categories[this.editingSOP]
            PutSOPCategory(sopData.id, sopData).then(response => {
              // 根据实际返回格式判断: { success: true, data: {...} }
              if (response.success || (response.data && response.data.success)) {
                const updatedCategory = response.data || response.data.data
                this.sop_categories.splice(this.editingSOP, 1, updatedCategory)
                this.sop_names = this.sop_categories.map(cat => cat.name)
                this.$message.success('修改成功')

                // 如果修改的是当前选中的SOP，更新当前选择
                if (this.sop_id === originalCategory.id) {
                  this.sop_name = updatedCategory.name
                }
                this.cancelEditSOP()
              } else {
                this.$message.error('修改失败')
              }
            }).catch(() => {
              this.$message.error('修改失败')
            })
          }
        }
      })
    },
    // 取消编辑SOP
    cancelEditSOP() {
      this.editingSOP = null
      this.sopManageForm = {
        id: null,
        name: '',
        description: '',
        icon: 'ai-robot',
        sort_order: 0,
        is_active: true,
        project_ids: []
      }
    },
    // 关闭SOP管理对话框
    handleCloseSopDialog() {
      this.cancelEditSOP()
      this.sopManageDialogVisible = false
    },
    // 回到顶层节点
    handleToTopNode() {
      this.listLoading = true
      this.current_expended_node = null
      this.expanded_ids = []

      // 清除当前SOP的展开状态
      const expandedKey = `${this.sop_id}_expanded_ids`
      const currentNodeKey = `${this.sop_id}_current_node`
      localStorage.removeItem(expandedKey)
      localStorage.removeItem(currentNodeKey)

      const params = []
      if (this.sop_id) {
        params.push(`sop_id=${this.sop_id}`)
      }
      if (this.keyword) {
        params.push(`keyword=${this.keyword}`)
      }

      const queryString = params.join('&')

      Tree('', queryString).then(response => {
        this.data = response.data.data
        this.total = response.data.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 根据ID搜索节点
    handleIDSearch(id) {
      if (!id) {
        this.handleToTopNode()
        return
      }
      this.listLoading = true
      // 重新加载树
      Tree('', `parent_id=${id}`).then(response => {
        this.data = response.data.data
        this.total = response.data.total
        Get(id).then(response => {
          this.current_expended_node = response.data
          console.log(this.current_expended_node)
          // 更新展开ID并保存状态
          this.expanded_ids = [id]
          this.saveExpandedState()
        }).catch(() => {
          // 处理错误
        }).finally(() => {
          this.listLoading = false
        })
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 通过父ID搜索节点
    handleSearchNodeByParentID(data) {
      // 如果children_count为0，不展开, 直接打开编辑框
      if (data.children_count === 0) {
        return
      }
      this.current_expended_node = data
      this.expanded_ids = [data.id]

      // 保存展开状态
      this.saveExpandedState()

      // 重新加载树
      Tree('', `parent_id=${data.id}`).then(response => {
        this.data = response.data.data
        this.total = response.data.total
      }).catch(() => {
        // 处理错误
      })
    },
    // 添加新模型
    showAddNewModel() {
      this.formTitle = '添加新模型'
      this.form = {
        id: '',
        name: '',
        sop: this.sop_id,
        sop_name: this.sop_name || '默认', // 保留用于向后兼容
        parent_id: '',
        parent_name: '',
        vip_grade: 0,
        disabled: false,
        engine: 'claude-3.7-sonnet',
        color: '#409EFF',
        position: '',
        placeholder: '',
        prompt: '',
        aiprompt_id: ''
      }
      this.formVisible = true
      this.activeTab = 'basic'
      this.usePromptTemplate = true
    },
    // 添加子节点
    append(data) {
      this.formTitle = `添加 ${data.name} 的子模型`
      this.form = {
        id: '',
        name: '',
        sop: data.sop || this.sop_id,
        sop_name: data.sop_name || this.sop_name || '默认', // 保留用于向后兼容
        parent_id: data.id,
        parent_name: data.name,
        disabled: false,
        engine: data.engine || 'claude-3.7-sonnet',
        color: data.color || '#409EFF',
        position: '',
        placeholder: '',
        prompt: '',
        aiprompt_id: ''
      }
      this.formVisible = true
      this.activeTab = 'basic'
      this.usePromptTemplate = true
    },
    // 编辑模型
    handleDirectlyEditModel(data) {
      this.formTitle = `编辑模型 - ${data.name}`
      this.formLoading = true
      this.dataloading = true
      Get(data.id).then(response => {
        this.form = response.data.data || response.data
        this.usePromptTemplate = !!this.form.aiprompt_id
        this.formLoading = false
        this.dataloading = false
        this.formVisible = true
        this.activeTab = 'basic'
        // 加载参考素材 - 在form设置完成后再加载
        this.$nextTick(() => {
          this.loadReferences()
        })
      }).catch((error) => {
        this.formLoading = false
        this.dataloading = false
        console.error('获取模型数据失败:', error)
        this.$message.error('获取模型数据失败: ' + (error.message || error))
      })
    },
    // 测试模型
    handleTestModel(data) {
      this.$message.info(`测试模型: ${data.name}`)
      // 实现模型测试功能
    },
    // 测试按钮处理
    handleTest() {
      if (!this.form.id) {
        this.$message.warning('请先保存模型后再进行测试')
        return
      }
      this.$message.info(`正在测试模型: ${this.form.name}`)
      // 实际测试功能实现
    },
    // 切换模型状态
    handleToggleStatus(data) {
      const newStatus = !data.disabled
      const updateData = { ...data, disabled: newStatus }

      Put(data.id, updateData).then(() => {
        data.disabled = newStatus
        this.$message.success(`模型已${newStatus ? '禁用' : '启用'}`)
      }).catch(() => {
        this.$message.error('更新状态失败')
      })
    },
    // 点击删除按钮
    handleClickDelete(data) {
      // 如果有子节点禁止删除
      if (data.children_count > 0) {
        this.$message.warning('请先删除子节点')
        return
      }
      this.deleteModel = data
      this.deleteVisible = true
    },
    // 确认删除
    confirmDelete() {
      this.deleteLoading = true
      Delete(this.deleteModel.id).then(() => {
        this.deleteLoading = false
        this.deleteVisible = false
        this.$message.success('删除成功')
        // 直接从当前数据删除，不用刷新
        this.data = this.data.filter(item => item.id !== this.deleteModel.id)
        // this.handleToTopNode()
      }).catch(() => {
        this.deleteLoading = false
        this.$message.error('删除失败')
      })
    },
    // 清空筛选
    handleClean() {
      this.keyword = ''
      this.engine = ''
      this.kwInput = ''
      this.handleSearch()
    },
    // 搜索
    handleSearch() {
      this.keyword = this.kwInput || this.keyword
      this.handleToTopNode()
    },
    // 保存模型数据
    handleSave() {
      this.formLoading = true
      this.saveSuccess = false

      // 准备提交数据：确保sop_id字段正确传递
      const submitData = { ...this.form }
      // 如果form.sop存在，将其作为sop_id发送给后端
      if (submitData.sop) {
        submitData.sop_id = submitData.sop
      }

      if (this.form.id) {
        // 更新现有模型
        Put(this.form.id, submitData).then(() => {
          this.formLoading = false
          this.saveSuccess = true
          setTimeout(() => {
            this.saveSuccess = false
          }, 2000)
          this.$message.success('保存成功')

          // 使用el-tree的方法更新节点
          this.updateNodeInTree(this.form)
        }).catch(() => {
          this.formLoading = false
          this.$message.error('保存失败')
        })
      } else {
        // 创建新模型
        Post(submitData).then((response) => {
          this.formLoading = false
          this.formVisible = false
          this.$message.success('创建成功')

          // 如果是添加子节点，更新父节点
          if (this.form.parent_id) {
            this.updateParentNodeChildrenCount(this.form.parent_id)
            this.handleIDSearch(this.form.parent_id)
          } else {
            // 添加顶层节点，刷新顶层
            const newNode = response.data || { ...this.form, id: new Date().getTime() }
            this.data.push(newNode)
          }
        }).catch(() => {
          this.formLoading = false
          this.$message.error('创建失败')
        })
      }
    },
    // 更新节点数据
    updateNodeInTree(updatedNode) {
      // 从el-tree中获取节点
      const node = this.$refs.ModelTree.getNode(updatedNode.id)

      if (node) {
        // 直接更新节点数据
        Object.assign(node.data, updatedNode)

        // 更新界面显示
        this.$set(node, 'data', { ...node.data })

        // 如果当前编辑的是展开的节点，也更新current_expended_node
        if (this.current_expended_node && this.current_expended_node.id === updatedNode.id) {
          Object.assign(this.current_expended_node, updatedNode)
        }

        return true
      } else {
        // 如果在当前加载的节点中找不到，尝试更新this.data
        for (let i = 0; i < this.data.length; i++) {
          if (this.data[i].id === updatedNode.id) {
            Object.assign(this.data[i], updatedNode)
            return true
          }
        }
      }

      return false
    },
    // 更新父节点的子节点数量
    updateParentNodeChildrenCount(parentId) {
      // 从el-tree中获取父节点
      const parentNode = this.$refs.ModelTree.getNode(parentId)

      if (parentNode) {
        // 增加子节点计数
        if (parentNode.data.children_count !== undefined) {
          parentNode.data.children_count += 1
        } else {
          parentNode.data.children_count = 1
        }

        // 更新界面显示
        this.$set(parentNode, 'data', { ...parentNode.data })

        // 如果节点已经展开，需要从后台重新加载子节点
        if (this.expanded_ids.includes(parentId)) {
          // 重新从后台加载子节点数据
          Tree(parentId, '').then(response => {
            // const children = response.data.data

            // 更新节点的子节点列表
            parentNode.childNodes = []
            this.$refs.ModelTree.store.load({
              node: parentNode,
              callback: () => {
                // 更新展开状态
                this.$refs.ModelTree.store.setExpandedKeys([parentId])

                // 如果是当前展开的节点，同步更新current_expended_node
                if (this.current_expended_node && this.current_expended_node.id === parentId) {
                  // 重新获取节点详情保证数据一致性
                  Get(parentId).then(response => {
                    this.current_expended_node = response.data
                    this.saveExpandedState()
                  })
                }
              }
            })
          }).catch(() => {
            this.$message.error('加载子节点失败')
          })
        }

        // 如果是当前展开的节点，也更新current_expended_node
        if (this.current_expended_node && this.current_expended_node.id === parentId) {
          this.current_expended_node.children_count = parentNode.data.children_count
        }

        return true
      } else {
        // 如果在当前加载的节点中找不到，尝试更新this.data
        for (let i = 0; i < this.data.length; i++) {
          if (this.data[i].id === parentId) {
            if (this.data[i].children_count !== undefined) {
              this.data[i].children_count += 1
            } else {
              this.data[i].children_count = 1
            }

            // 如果是当前顶层节点，需要从后台重新加载
            if (this.current_expended_node === null || this.current_expended_node.id === this.data[i].id) {
              Tree(parentId, '').then(response => {
                const children = response.data.data
                // 更新节点的子节点列表
                this.data[i].children = children
                // 强制更新视图
                this.$forceUpdate()
              })
            }

            return true
          }
        }
      }

      return false
    },
    // 提示词类型变更
    handlePromptTypeChange(value) {
      if (value) {
        // 使用模板ID
        this.form.prompt = ''
      } else {
        // 使用自定义提示词
        this.form.aiprompt_id = ''
      }
    },
    // 远程搜索AI提示词模板
    remoteSearchAiPrompt(query) {
      if (query) {
        this.aipromptLoading = true
        // 这里需要根据实际情况添加搜索AI提示词模板的API调用
        setTimeout(() => {
          this.aipromptLoading = false
          this.aiprompts = [
            { id: 1, name: '营销文案生成器' },
            { id: 2, name: '产品描述优化器' },
            { id: 3, name: '客户反馈分析器' }
          ]
        }, 200)
      } else {
        this.aiprompts = []
      }
    },
    // 获取AI引擎列表
    getAiEngines() {
      GetAiPrompt(null, qs.stringify({
        pagesize: 1,
        page: 1
      })).then(response => {
        if (response.data && response.data.ai_engines) {
          // 确保默认引擎存在
          const hasDefaultEngine = response.data.ai_engines.some(engine => engine.value === 'gpt-3.5-turbo')
          if (!hasDefaultEngine) {
            response.data.ai_engines.unshift({
              label: 'claude-3.7-sonnet',
              value: 'claude-3.7-sonnet'
            })
          }

          // 过滤重复的引擎
          const uniqueValues = new Set()
          const uniqueEngines = response.data.ai_engines.filter(engine => {
            if (uniqueValues.has(engine.value)) {
              return false
            } else {
              uniqueValues.add(engine.value)
              return true
            }
          })

          this.ai_engines = uniqueEngines
        }
      }).catch(() => {
        // 请求失败时使用默认值
        console.error('获取AI引擎列表失败，使用默认值')
      })
    },
    // 插入用户内容
    insertUserContent() {
      // 确定哪个编辑器是当前活动的
      let editor = null
      if (this.activeTab === 'prompt' && !this.usePromptTemplate) {
        // 获取提示词编辑器
        editor = this.$refs.promptEditor
        if (!editor) {
          // 尝试通过DOM获取编辑器
          const editorElem = document.querySelector('.prompt-editor .v-note-wrapper .v-note-panel .v-note-edit .auto-textarea-wrapper textarea')
          if (editorElem) {
            const startPos = editorElem.selectionStart
            const endPos = editorElem.selectionEnd
            const text = this.form.prompt

            // 在光标位置插入{{user_content}}
            this.form.prompt = text.substring(0, startPos) +
                              '<user_content>{{user_content}}</user_content>' +
                              text.substring(endPos)

            // 重新设置光标位置
            this.$nextTick(() => {
              editorElem.focus()
              editorElem.selectionStart = startPos + 16 // '{{user_content}}'.length
              editorElem.selectionEnd = startPos + 16
            })
            return
          }
        }
      } else if (this.activeTab === 'output') {
        // 获取输出模板编辑器
        editor = this.$refs.outputEditor
        if (!editor) {
          // 尝试通过DOM获取编辑器
          const editorElem = document.querySelector('.el-tab-pane.output .editor-container .v-note-wrapper .v-note-panel .v-note-edit .auto-textarea-wrapper textarea')
          if (editorElem) {
            const startPos = editorElem.selectionStart
            const endPos = editorElem.selectionEnd
            const text = this.form.output_template || ''

            // 在光标位置插入{{user_content}}
            this.form.output_template = text.substring(0, startPos) +
                                      '{{user_content}}' +
                                      text.substring(endPos)

            // 重新设置光标位置
            this.$nextTick(() => {
              editorElem.focus()
              editorElem.selectionStart = startPos + 16 // '{{user_content}}'.length
              editorElem.selectionEnd = startPos + 16
            })
            return
          }
        }
      }

      // 如果找到编辑器实例，使用其API插入文本
      if (editor) {
        // 使用mavon-editor的内部方法
        editor.$refs.toolbar_left.$parent.insertText('{{user_content}}')
      } else {
        // 兜底方案: 使用基于当前活动标签页选择要更新的属性
        if (this.activeTab === 'prompt' && !this.usePromptTemplate) {
          this.form.prompt = (this.form.prompt || '') + '{{user_content}}'
        } else if (this.activeTab === 'output') {
          this.form.output_template = (this.form.output_template || '') + '{{user_content}}'
        }
      }
    },

    // ========== 参考素材相关方法 ==========
    // 加载参考素材列表
    loadReferences() {
      if (!this.form.id) return

      this.referencesLoading = true
      getReferences(this.form.id).then(response => {
        if (response.success) {
          this.references = response.data || []
        } else {
          this.$message.error(response.msg || '加载参考素材失败')
        }
      }).catch(error => {
        console.error('加载参考素材失败:', error)
        this.$message.error('加载参考素材失败')
      }).finally(() => {
        this.referencesLoading = false
      })
    },

    // 直接插入文件 - 参考 crmorderattachments 的实现
    async handleInsertFile(item) {
      try {
        const referenceData = {
          tree_id: this.form.id,
          file_id: item.id,
          filename: item.filename,
          file_url: item.url,
          file_type: this.getFileTypeFromUrl(item.url) || item.content_type,
          description: '',
          position: this.references.length
        }

        const response = await addReference(referenceData)
        if (response.success) {
          this.$message.success('文件添加成功')
          this.loadReferences()
        } else {
          this.$message.error(response.msg || '添加文件失败')
        }
      } catch (error) {
        console.error('添加文件失败:', error)
        this.$message.error('添加文件失败')
      }
    },

    // 文件类型判断方法
    isImageFile(item) {
      if (item.file_type && item.file_type.startsWith('image/')) return true
      if (item.filename) {
        const ext = item.filename.toLowerCase().split('.').pop()
        return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)
      }
      return false
    },

    isPDF(filename) {
      return filename && filename.toLowerCase().endsWith('.pdf')
    },

    isExcel(filename) {
      if (!filename) return false
      const ext = filename.toLowerCase().split('.').pop()
      return ['xls', 'xlsx'].includes(ext)
    },

    isWord(filename) {
      if (!filename) return false
      const ext = filename.toLowerCase().split('.').pop()
      return ['doc', 'docx'].includes(ext)
    },

    // 文件名截断
    truncateFileName(filename, maxLength = 15) {
      if (!filename || filename.length <= maxLength) return filename
      const ext = filename.split('.').pop()
      const name = filename.substring(0, filename.lastIndexOf('.'))
      const truncated = name.substring(0, maxLength - ext.length - 3) + '...'
      return truncated + '.' + ext
    },

    // 格式化短日期
    formatShortDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${month}-${day}`
    },

    // 从 URL 获取文件类型
    getFileTypeFromUrl(url) {
      if (!url) return 'file'
      const ext = url.split('.').pop().toLowerCase()
      if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) return 'image'
      if (['pdf'].includes(ext)) return 'document'
      if (['mp4', 'avi', 'mov', 'wmv'].includes(ext)) return 'video'
      if (['xls', 'xlsx', 'doc', 'docx'].includes(ext)) return 'document'
      return 'file'
    },

    // 选中状态判断
    isReferenceSelected(item) {
      return this.selectedReferences.some(ref => ref.id === item.id)
    },

    // 文件卡片点击事件
    handleFileCardClick(item, event) {
      if (event.ctrlKey || event.metaKey) {
        // Ctrl/Cmd + 点击：多选
        const index = this.selectedReferences.findIndex(ref => ref.id === item.id)
        if (index > -1) {
          this.selectedReferences.splice(index, 1)
        } else {
          this.selectedReferences.push(item)
        }
      } else {
        // 普通点击：单选
        this.selectedReferences = [item]
      }
    },

    // 图片预览
    previewImage(url) {
      this.currentPreviewImage = url
      this.imagePreviewVisible = true
    },

    // 复制图片链接
    copyImageUrl() {
      if (this.currentPreviewImage) {
        const textarea = document.createElement('textarea')
        textarea.value = this.currentPreviewImage
        textarea.style.position = 'fixed'
        textarea.style.opacity = '0'
        document.body.appendChild(textarea)
        textarea.select()

        try {
          const successful = document.execCommand('copy')
          if (successful) {
            this.$message.success('图片链接已复制到剪贴板')
          } else {
            this.$message.error('复制失败，请手动复制')
          }
        } catch (err) {
          console.error('复制失败:', err)
          this.$message.error('复制失败，请手动复制')
        } finally {
          document.body.removeChild(textarea)
        }
      }
    },

    // 下载文件
    downloadFile(item) {
      const link = document.createElement('a')
      link.href = item.file_url
      link.download = item.filename || '下载文件'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    // 上传前检查
    beforeUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.error('文件大小不能超过 50MB!')
      }
      return isLt50M
    },

    // 上传成功
    handleUploadSuccess(response, file, fileList) {
      if (response.success) {
        this.$message.success('文件上传成功')
        this.fileList = fileList
      } else {
        this.$message.error(response.msg || '文件上传失败')
      }
    },

    // 上传失败
    handleUploadError(error, file) {
      console.error('文件上传失败:', error)
      this.$message.error('文件上传失败')
    },

    // 处理文件上传成功
    handleFileUploaded(file) {
      this.uploadedFiles.push(file)
      this.$message.success(`文件 ${file.filename} 上传成功`)
    },
    // 确认添加参考素材
    async confirmAddReferences() {
      const filesToAdd = []

      // 收集选中的已有文件
      this.selectedFiles.forEach(file => {
        filesToAdd.push({
          tree_id: this.form.id,
          file_id: file.id
        })
      })

      // 收集上传的新文件
      this.uploadedFiles.forEach(file => {
        filesToAdd.push({
          tree_id: this.form.id,
          file_id: file.id
        })
      })

      if (filesToAdd.length === 0) {
        this.$message.warning('请选择要添加的文件')
        return
      }

      // 批量添加参考素材
      const promises = filesToAdd.map(data => {
        return addReference(data)
      })

      Promise.all(promises).then(responses => {
        const successCount = responses.filter(r => r.success).length
        if (successCount > 0) {
          this.$message.success(`成功添加 ${successCount} 个参考素材`)
          this.loadReferences()
          this.uploadDialogVisible = false
          this.selectedFiles = []
          this.uploadedFiles = []
        }
      }).catch(error => {
        console.error('添加参考素材失败:', error)
        this.$message.error('添加参考素材失败')
      })
    },

    // 选择参考素材
    handleReferenceSelectionChange(selection) {
      this.selectedReferences = selection
    },

    // 更新参考素材位置
    updateReferencePosition(reference) {
      updateReference(reference.id, {
        position: reference.position
      }).then(response => {
        if (response.success) {
          this.$message.success('排序更新成功')
        }
      }).catch(error => {
        console.error('更新排序失败:', error)
      })
    },

    // 更新参考素材标题
    updateReferenceTitle(reference) {
      updateReference(reference.id, {
        title: reference.title
      }).then(response => {
        if (!response.success) {
          this.$message.error('更新标题失败')
        }
      }).catch(error => {
        console.error('更新标题失败:', error)
      })
    },

    // 更新参考素材描述
    updateReferenceDescription(reference) {
      updateReference(reference.id, {
        description: reference.description
      }).then(response => {
        if (!response.success) {
          this.$message.error('更新描述失败')
        }
      }).catch(error => {
        console.error('更新描述失败:', error)
      })
    },

    // 删除参考素材
    deleteReference(reference) {
      this.$confirm('确定要删除该参考素材吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteReference(reference.id).then(response => {
          if (response.success) {
            this.$message.success('删除成功')
            this.loadReferences()
          } else {
            this.$message.error(response.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除参考素材失败:', error)
          this.$message.error('删除失败')
        })
      })
    },

    // 批量删除参考素材
    batchDeleteReferences() {
      if (this.selectedReferences.length === 0) {
        this.$message.warning('请选择要删除的参考素材')
        return
      }

      this.$confirm(`确定要删除选中的 ${this.selectedReferences.length} 个参考素材吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selectedReferences.map(r => r.id)
        batchReferences({
          action: 'delete_batch',
          ids: ids
        }).then(response => {
          if (response.success) {
            this.$message.success(response.msg)
            this.loadReferences()
            this.selectedReferences = []
          } else {
            this.$message.error(response.msg || '批量删除失败')
          }
        }).catch(error => {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        })
      })
    },

    // 获取文件类型标签样式
    getFileTypeTagType(fileType) {
      const typeMap = {
        'image': 'success',
        'document': 'primary',
        'video': 'warning',
        'other': 'info'
      }
      return typeMap[fileType] || 'info'
    },

    // 获取文件类型标签文本
    getFileTypeLabel(fileType) {
      const labelMap = {
        'image': '图片',
        'document': '文档',
        'video': '视频',
        'other': '其他'
      }
      return labelMap[fileType] || '其他'
    },

    // ========== 粘贴上传相关方法 ==========
    // 聚焦粘贴区域
    focusPasteArea() {
      this.$nextTick(() => {
        if (this.$refs.pasteArea) {
          this.$refs.pasteArea.focus()
        }
      })
    },

    // 处理粘贴事件
    handlePaste(event) {
      const clipboardData = event.clipboardData || window.clipboardData
      const items = clipboardData.items

      let hasImage = false

      for (let i = 0; i < items.length; i++) {
        const item = items[i]

        // 检查是否为图片
        if (item.type.indexOf('image') !== -1) {
          hasImage = true
          const file = item.getAsFile()

          if (file) {
            this.processPastedImage(file)
          }
        }
      }

      if (hasImage) {
        // 阻止默认粘贴行为
        event.preventDefault()
        // 清空textarea内容
        this.pasteAreaText = ''
      }
    },

    // 处理粘贴的图片
    processPastedImage(file) {
      // 检查文件大小
      if (file.size > 50 * 1024 * 1024) {
        this.$message.error('图片大小不能超过 50MB!')
        return
      }

      // 生成预览URL
      const reader = new FileReader()
      reader.onload = (e) => {
        const timestamp = new Date().getTime()
        const randomStr = Math.random().toString(36).substring(2, 8)
        const fileName = `paste_image_${timestamp}_${randomStr}.${this.getImageExtension(file.type)}`

        const imageData = {
          file: file,
          dataUrl: e.target.result,
          name: fileName,
          type: file.type,
          size: file.size
        }

        this.pastedImages.push(imageData)
        this.$message.success('图片粘贴成功！')
      }

      reader.onerror = () => {
        this.$message.error('图片读取失败')
      }

      reader.readAsDataURL(file)
    },

    // 获取图片扩展名
    getImageExtension(mimeType) {
      const extensions = {
        'image/jpeg': 'jpg',
        'image/jpg': 'jpg',
        'image/png': 'png',
        'image/gif': 'gif',
        'image/webp': 'webp',
        'image/bmp': 'bmp',
        'image/svg+xml': 'svg'
      }
      return extensions[mimeType] || 'png'
    },

    // 删除粘贴的图片
    removePastedImage(index) {
      this.pastedImages.splice(index, 1)
      this.$message.success('图片已删除')
    },

    // 上传粘贴的图片
    async uploadPastedImages() {
      if (this.pastedImages.length === 0) {
        return []
      }

      const uploadPromises = this.pastedImages.map(async(imageData) => {
        const formData = new FormData()
        formData.append('file', imageData.file, imageData.name)
        formData.append('project_id', this.$store.getters.projectId)

        try {
          const response = await request({
            url: this.uploadUrl,
            method: 'post',
            data: formData,
            headers: {
              ...this.uploadHeaders,
              'Content-Type': 'multipart/form-data'
            }
          })

          if (response.success) {
            return response.data.id
          } else {
            throw new Error(response.msg || '上传失败')
          }
        } catch (error) {
          console.error('粘贴图片上传失败:', error)
          this.$message.error(`图片 ${imageData.name} 上传失败`)
          return null
        }
      })

      const uploadedIds = await Promise.all(uploadPromises)
      return uploadedIds.filter(id => id !== null)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  height: 100vh;
  display: flex;
  flex-direction: column;

  .el-container {
    height: calc(100% - 60px);
  }
}

.fixed-aside {
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
  padding: 15px;
  height: 100%;
  overflow-y: auto;

  .el-tree {
    margin-top: 10px;
    font-size: 13px;

    :deep(.el-tree-node__content) {
      height: auto;
      min-height: 28px;
      padding: 2px 0;
    }

    :deep(.el-tree-node__expand-icon) {
      padding: 6px;
    }
  }
}

.scrollable-main {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;

  .el-card {
    margin-bottom: 20px;
  }
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 100%;
  position: relative;

  &:hover {
    .node-info-actions {
      opacity: 1;
      visibility: visible;
    }
  }
}

.node-title {
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
  padding-right: 2px;
  width: 100%;
  overflow: hidden;

  .name-text {
    margin-right: 5px;
    font-weight: 500;
    word-break: break-word;
    white-space: normal;
    line-height: 1.3;
    font-size: 13px;

    &.disabled {
      text-decoration: line-through;
      opacity: 0.7;
    }

    &.editing {
      color: #f56c6c;
      font-weight: bold;
      text-decoration: underline;
    }
  }

  .children-count {
    font-size: 11px;
    color: #909399;
    background-color: #f0f2f5;
    border-radius: 10px;
    padding: 1px 5px;
    margin-left: 3px;
    margin-top: 2px;
  }
}

.node-info-actions {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  opacity: 0;
  visibility: hidden;
  transition: all 0.2s ease;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  z-index: 10;

  .node-actions {
    display: flex;
    align-items: center;
    gap: 4px;

    .el-button {
      padding: 4px 8px;
      margin: 0;

      &.el-button--mini {
        font-size: 12px;
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }
}

.custom-row {
  margin-bottom: 10px;

  .row-title {
    font-weight: bold;
    margin-right: 10px;
  }
}

.color-selection-container {
  display: flex;
  align-items: center;

  .color-preview {
    width: 20px;
    height: 20px;
    border-radius: 4px;
    margin-left: 10px;
    border: 1px solid #dcdfe6;
  }

  .color-help-icon {
    margin-left: 10px;
    color: #909399;
    cursor: pointer;
  }
}

.color-dot {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

.form-section {
  margin-bottom: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 12px;
  background-color: #fff;

  .section-title {
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 12px;
    color: #606266;
    border-bottom: 1px solid #ebeef5;
    padding-bottom: 8px;
  }

  &.parent-section {
    background-color: #fafafa;
    margin-bottom: 16px;
  }
}

.form-flex-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: flex-start;

  .form-item-flex {
    flex: 1;
    min-width: 180px;
    margin-bottom: 0;

    :deep(.el-form-item__label) {
      padding-bottom: 4px;
      line-height: 20px;
    }

    :deep(.el-form-item__content) {
      line-height: 32px;
    }
  }

  .form-item-small {
    width: 100px;
    min-width: 100px;
    margin-bottom: 0;
  }

  .form-item-medium {
    flex: 1;
    min-width: 180px;
    margin-bottom: 0;
  }
}

.form-inline-group {
  display: flex;
  align-items: center;
  gap: 8px;

  .parent-tag {
    margin: 0;
  }

  .parent-id-input {
    width: 180px;
  }
}

:deep(.el-form-item) {
  margin-bottom: 12px;
}

:deep(.el-form-item__label) {
  padding-bottom: 4px;
  line-height: 20px;
}

:deep(.el-tabs__header) {
  margin-bottom: 12px;
}

:deep(.el-form--label-top .el-form-item__label) {
  padding: 0 0 4px;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;

  :deep(.el-textarea__inner) {
    border: none;
    padding: 8px;
  }
}

.prompt-textarea {
  font-family: monospace;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2px;
  padding: 3px 5px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}

.navigation-wrapper {
  display: flex;
  align-items: center;
  padding: 10px 0;
  flex-wrap: wrap;

  .nav-button {
    font-size: 14px;
    padding: 0 10px;

    &:hover {
      color: #409EFF;
    }
  }

  .el-divider--vertical {
    margin: 0 10px;
  }

  .add-sub-button {
    margin-left: 15px;
  }

  .current-node-name {
    font-weight: 500;
    color: #303133;
    margin-right: 10px;
  }

  .node-action-buttons {
    display: flex;
    margin-left: auto;
    gap: 8px;

    .el-button {
      padding: 5px 10px;
    }
  }
}

.md-editor {
  height: 400px;
  z-index: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;

  :deep(.v-note-wrapper) {
    z-index: auto;
    min-height: 300px;
  }

  :deep(.v-note-panel) {
    box-shadow: none !important;
  }
}

.empty-state {
  text-align: center;
  padding: 100px 20px;
}

// 参考素材相关样式
.references-container {
  padding: 10px 0;

  .compact-toolbar {
    margin: 10px 0;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
  }

  .files-grid-container {
    margin-top: 10px;
  }

  .compact-file-card {
    border: 1px solid #e8e8e8;
    border-radius: 6px;
    padding: 8px;
    background: #fff;
    cursor: pointer;
    transition: all 0.2s ease;
    position: relative;
    height: 180px;
    display: flex;
    flex-direction: column;

    &:hover {
      border-color: #409EFF;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);

      .file-actions {
        opacity: 1;
      }
    }

    &.selected {
      border-color: #409EFF;
      background: #f0f8ff;
    }
  }

  .file-icon-container {
    flex: 0 0 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;
  }

  .small-file-icon {
    width: 60px;
    height: 60px;
    border-radius: 4px;
  }

  .image-preview-container {
    cursor: pointer;
    transition: transform 0.2s;

    &:hover {
      transform: scale(1.05);
    }
  }

  .image-error {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    height: 60px;
    background: #f5f5f5;
    border-radius: 4px;
    color: #ccc;
    font-size: 24px;
  }

  .file-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .file-name {
    font-size: 12px;
    font-weight: 500;
    color: #303133;
    line-height: 1.2;
    word-break: break-all;
    text-align: center;
  }

  .file-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 10px;
    color: #909399;
    margin-bottom: 4px;
  }

  .file-type {
    background: #f0f0f0;
    padding: 1px 4px;
    border-radius: 2px;
    font-size: 9px;
  }

  .file-actions {
    position: absolute;
    top: 4px;
    right: 4px;
    display: flex;
    gap: 4px;
    opacity: 0;
    transition: opacity 0.2s;

    .el-button {
      padding: 2px 4px;
      min-height: auto;
      border: none;
      background: rgba(255, 255, 255, 0.9);
      border-radius: 3px;

      &.danger-btn {
        color: #f56c6c;

        &:hover {
          background: #f56c6c;
          color: white;
        }
      }
    }
  }

  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #909399;

    p {
      margin-top: 10px;
      font-size: 14px;
    }
  }

  // 图片预览对话框样式
  .image-preview-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 200px;
  }
}

.upload-container {
  .file-search {
    margin-bottom: 10px;
  }

  .upload-demo {
    ::v-deep .el-upload-dragger {
      width: 100%;
      height: 200px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;

      .el-icon-upload {
        font-size: 50px;
        color: #C0C4CC;
        margin-bottom: 10px;
      }
    }
  }
}

// 粘贴上传相关样式
.paste-upload-area {
  position: relative;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  text-align: center;
  padding: 30px;
  margin-bottom: 20px;
  cursor: pointer;
  transition: border-color 0.3s ease;

  &:hover {
    border-color: #409EFF;
    background-color: #f0f9ff;
  }

  .paste-hint {
    position: relative;
    z-index: 2;
    pointer-events: none;
  }

  .paste-textarea {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    border: none;
    outline: none;
    resize: none;
    background: transparent;
    cursor: pointer;
    z-index: 1;
  }
}

.paste-upload-area.focused {
  border-color: #409EFF;
  background-color: #f0f9ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.pasted-images {
  margin-bottom: 20px;

  .pasted-images-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 10px;
    margin-top: 10px;
  }

  .pasted-image-item {
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;

    img {
      width: 100%;
      height: 100px;
      object-fit: cover;
      display: block;
    }

    .pasted-image-overlay {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
      color: white;
      padding: 8px 4px 4px;
      display: flex;
      justify-content: space-between;
      align-items: flex-end;

      .pasted-image-name {
        font-size: 10px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        margin-right: 4px;
      }

      .el-button {
        padding: 2px;
        min-height: auto;
      }
    }
  }
}

.info-table {
  .el-row {
    margin-bottom: 10px;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
